package com.dddd.blog.blogcommon.config.redis;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author 喵星球的大橘
 */
@Configuration
public class RedisConfig {

    /**
     *
     * @param factory
     * @return
     */
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory factory){

        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        // Redis连接工厂
        redisTemplate.setConnectionFactory(factory);

        // json序列化
        Jackson2JsonRedisSerializer<Object> jacksoSerializer = new Jackson2JsonRedisSerializer(Object.class);

        //String序列化

        StringRedisSerializer stringSerializer = new StringRedisSerializer();

        // key使用string序列化
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);

        // value使用json序列化
        redisTemplate.setValueSerializer(jacksoSerializer);
        redisTemplate.setHashValueSerializer(jacksoSerializer);

        redisTemplate.afterPropertiesSet();

        return redisTemplate;
    }

    /**
     * stringRedisTemplate采用String得序列化
     * @return
     */
    @Bean
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory){

        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(factory);

        return stringRedisTemplate;
    }
}
